package com.my.socket.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.SocketFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * User: Alex Zhong
 * Date: 2016/6/17
 */
public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    private String host;
    private int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        List<Thread> threads = new ArrayList<Thread>();

        for (int i = 0; i < 10; i++) {
            FutureTask futureTask = new FutureTask(new Callable() {
                @Override
                public Void call() throws Exception {
                    Client client = new Client("127.0.0.1", 9999);
                    client.access();
                    return null;
                }
            });
            Thread thread = new Thread(futureTask);
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }

    public void access() throws Exception {
        SocketFactory socketFactory = SocketFactory.getDefault();
        Socket socket = socketFactory.createSocket(this.host, this.port);

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream));
        String message = "Hello, I am Alex";
        printWriter.println(message);
        printWriter.flush();
        LOGGER.info("send the message [{}] to the server", message);

        InputStream inputStream = socket.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        message = bufferedReader.readLine();
        LOGGER.info("receive the message [{}] from the server", message);

        socket.close();
    }
}
